package com.gree.shyun.util;

import com.gree.shyun.bean.VMLayoutBean;
import com.alibaba.fastjson.JSON;
import com.gree.shyun.server.generatingcode.TemplateUtil;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.util.*;

public class VMActivityHelper {
    private static String packageName = "com.gree.shyun";
    public static void doInit(String path,String basePath){
        //转databinding开关
        boolean openReplaceTag = true;
        //转vm开关
        boolean toVM = true;
        String layoutPath = path;
        File layoutfile = new File(layoutPath);
        String mPath = layoutfile.getParent();
        ArrayList<File> files=new ArrayList<>();
            try {
                getFiles(mPath, files,  "Frm");
                for (File file : files) {
                    String activity = file.getName().substring(0, file.getName().indexOf("."));
                    List<String> lines = FileUtils.readLines(file);
                    boolean shouldWriteModel = false;
                    String fileText = "";
                    String lastImport = "";
                    String shouldImport = "";
                    String pkg = "";
                    if (lines.size() > 0) {
                        pkg = lines.get(0);
                    }


                    boolean hasFind = false;
                    boolean hasEnd = false;
                    String afterLine = "";
                    int firstIndex = 0, endIndex = 0;
                    int inds = 0;
                    for (String s : lines) {
                        if (s.startsWith("public class")) {
                            hasFind = true;
                            firstIndex = inds;
                        }
                        if (hasFind && !hasEnd) {
                            afterLine += s.trim() + " ";
                        }
                        if (!hasEnd && hasFind && s.endsWith("{")) {
                            hasEnd = true;
                            endIndex = inds;
                        }
                        inds++;
                    }

                    boolean isFirsts = true;
                    List<String> newLines = new ArrayList<>();
                    boolean shouldAdd;
                    for(int i = 0 ;i<lines.size();i++){
                        if(i>=firstIndex&&i<=endIndex){
                            if (isFirsts) {
                                isFirsts = false;
                                shouldAdd = true;
                                lines.set(i, afterLine);
                            } else {
                                shouldAdd = false;
                            }
                        }else{
                            shouldAdd = true;
                        }
                        if(shouldAdd) {
                            newLines.add(lines.get(i));
                        }
                    }

                    lines = new ArrayList<>(newLines);


                    int i = 0;
//                //收集view id
                    List<VMLayoutBean> vmLayoutBeans = new ArrayList<>();
                    List<VMLayoutBean> findByIds = new ArrayList<>();
                    Set<String> shouldDelete = new HashSet<>();
                    for (String line : lines) {
                        i++;

                        if(openReplaceTag) {
                            String trline = line.trim();
                            trline = CommonUtil.replaceXsf(trline);
                            if (!" ".equals(trline) && trline.length() > 1) {
                                if (trline.startsWith("@Bind")) {
                                    if (i < lines.size()) {
                                        shouldDelete.add(line);
                                        String nextLine = lines.get(i).trim();
                                        nextLine = CommonUtil.replaceXsf(nextLine);
                                        String layoutId = CommonUtil.getMiddleStr(trline, "@Bind\\(R\\.id\\.", "\\)");
                                        VMLayoutBean vmLayoutBean = new VMLayoutBean();
                                        vmLayoutBean.setLayoutId(layoutId);
                                        String[] vs = nextLine.substring(0, nextLine.length() - 1).split(" ");
                                        if (vs.length > 1) {
                                            vmLayoutBean.setLayoutName(vs[1]);
                                            vmLayoutBean.setLayoutType(vs[0]);
                                        }
                                        vmLayoutBeans.add(vmLayoutBean);
                                    }
                                }
                                if (trline.contains(" ") && !trline.contains("=")) {
                                    String[] vs = trline.split(" ");
                                    if (vs.length > 1) {
                                        if (!"View".equals(vs[0])) {
                                            if (CommonUtil.endWIdth(vs[0], "View", "Layout", "EditText", "Group", "ViewSwitcher", "Button", "Switch",
                                                    "ProgressBar", "SeekBar", "TableRow", "Pager", "ProgressWheel", "WeekBar", "WithHole",
                                                    "Radio", "SliderBar", "CheckBox")) {
                                                String r = vs[1];
                                                if (r.length() > 1) {
                                                    shouldDelete.add(line);
                                                    System.out.println("shouldDelete->" + line);
                                                    String right = r.substring(0, r.length() - 1).trim();
                                                    if (right.contains(",")) {
                                                        String[] rights = right.split(",");
                                                        for (String s : rights) {
                                                            VMLayoutBean vmLayoutBean = new VMLayoutBean();
                                                            vmLayoutBean.setLayoutType(vs[0].trim());
                                                            vmLayoutBean.setLayoutName(s.trim());
                                                            vmLayoutBeans.add(vmLayoutBean);
                                                        }
                                                    } else {
                                                        VMLayoutBean vmLayoutBean = new VMLayoutBean();
                                                        vmLayoutBean.setLayoutType(vs[0].trim());
                                                        vmLayoutBean.setLayoutName(right);
                                                        vmLayoutBeans.add(vmLayoutBean);
                                                    }
                                                }

                                            }
                                        }
                                    }
                                }
                                if (trline.contains("findViewById")) {
                                    shouldDelete.add(line);
                                    String[] ss = trline.split("=");
                                    VMLayoutBean vmLayoutBean = new VMLayoutBean();
                                    vmLayoutBean.setLayoutName(ss[0].trim());
                                    String layoutId = CommonUtil.getMiddleStr(ss[1], "findViewById\\(R\\.id\\.", "\\)");
                                    vmLayoutBean.setLayoutId(layoutId.trim());
                                    findByIds.add(vmLayoutBean);
                                }
                            }

                        }

                        if(toVM) {

                            if (line.startsWith("import")) {
                                lastImport = line;
                            }
                            if (line.startsWith("public class")) {
                                if (line.contains("BasePageActivity<") || line.contains("BasePageFragment<")) {
                                    continue;
                                }
                                if (line.contains("BasePageActivity")) {
                                    shouldWriteModel = true;
                                    String layout = "";
                                    for (String l1 : lines) {
                                        if (l1.contains("setContentView")) {
                                            List<String> layoutName = CommonUtil.getMiddle(l1, "setContentView\\(R\\.layout\\.", "\\)\\;");
                                            if (layoutName.size() > 0) {
                                                String[] split = layoutName.get(0).split("_");
                                                for (String s : split) {
                                                    layout += CommonUtil.firstToUpperCase(s);
                                                }
                                            }
                                            break;
                                        }
                                    }
                                    layout += "Binding";
                                    line = line.replaceAll("BasePageActivity", "BasePageActivity<" + activity + "ViewModel," + layout + ">");
                                    line = "@AndroidEntryPoint\n" + line;

                                    shouldImport += "import dagger.hilt.android.AndroidEntryPoint;\n";
                                    pkg = pkg.trim();
                                    String pack = pkg.substring(0, pkg.length() - 1);
                                    pack = pack.replaceAll("package", "import");
                                    pack += "." + activity + "ViewModel;";
                                    shouldImport += "import dagger.hilt.android.AndroidEntryPoint;\n";
                                    shouldImport += pack + "\n";
                                    shouldImport += "import "+packageName+".databinding." + layout + ";\n";
                                }

                                if (line.contains("BasePageFragment")) {
                                    shouldWriteModel = true;
                                    String layout = "";
                                    for (String l1 : lines) {
                                        if (l1.contains("return R.layout.")) {
                                            List<String> layoutName = CommonUtil.getMiddle(l1, "return R\\.layout\\.", "\\;");
                                            if (layoutName.size() > 0) {
                                                String[] split = layoutName.get(0).split("_");
                                                for (String s : split) {
                                                    layout += CommonUtil.firstToUpperCase(s);
                                                }
                                            }
                                            break;
                                        }
                                    }
                                    layout += "Binding";
                                    line = line.replaceAll("BasePageFragment", "BasePageFragment<" + activity + "ViewModel," + layout + ">");
                                    line = "@AndroidEntryPoint\n" + line;

                                    shouldImport += "import dagger.hilt.android.AndroidEntryPoint;\n";
                                    pkg = pkg.trim();
                                    String pack = pkg.substring(0, pkg.length() - 1);
                                    pack = pack.replaceAll("package", "import");
                                    pack += "." + activity + "ViewModel;";
                                    shouldImport += "import dagger.hilt.android.AndroidEntryPoint;\n";
                                    shouldImport += pack + "\n";
                                    shouldImport += "import "+packageName+".databinding." + layout + ";\n";
                                }
                            }
                            if (line.contains("setContentView")) {
                                if (!line.contains("setContentViewRes")) {
                                    line = line.replaceAll("setContentView", "setContentViewRes");
                                }
                            }
                        }else{
                            if (line.startsWith("public class")) {
                                if (line.contains("BasePageActivity") || line.contains("BasePageFragment")) {
                                    shouldWriteModel = true;
                                }
                            }
                        }

                        if(openReplaceTag) {
                            if (line.contains("rightImg")) {
                                line = line.replaceAll("rightImg", "baseBinding.rightImg");
                            }
                        }
                        fileText += line + "\n";
                    }


                    if(openReplaceTag) {
                        if (shouldDelete.size() > 0) {
                            String[] li = fileText.split("\n");
                            fileText = "";
                            for (int a = 0; a < li.length; a++) {
                                if (CommonUtil.isIn(shouldDelete, li[a])) {
                                    System.out.println("删除" + li[a]);
                                    continue;
                                }
                                fileText += li[a] + "\n";
                            }
                        }
                    }

                    if(toVM) {
                        fileText = fileText.replaceAll(lastImport, lastImport + "\n" + shouldImport);
                    }
                    if (shouldWriteModel) {

                        if(openReplaceTag) {
                            for (int a = 0; a < vmLayoutBeans.size(); a++) {
                                VMLayoutBean v = CommonUtil.findByName(findByIds, vmLayoutBeans.get(a).getLayoutName());
                                if (v != null) {
                                    vmLayoutBeans.get(a).setLayoutId(v.getLayoutId());
                                    System.out.println("组合:" + JSON.toJSONString(vmLayoutBeans.get(a)));
                                }
                            }

                            System.out.println("需要替换的所有对象:" + JSON.toJSONString(vmLayoutBeans));
                            synchronized (VMActivityHelper.class) {
                                for (VMLayoutBean v : vmLayoutBeans) {
                                    String id = v.getLayoutId();
                                    if (id == null) {
                                        continue;
                                    }
                                    if (id.contains("_")) {
                                        String[] ids = id.split("_");
                                        id = "";
                                        boolean isFirst = true;
                                        for (String d : ids) {
                                            if (isFirst) {
                                                char firstCode = d.charAt(0);
                                                if (!Character.isUpperCase(firstCode)) {
                                                    id += d;
                                                } else {
                                                    id += CommonUtil.firstToUpperCase(d);
                                                }
                                            } else {
                                                id += CommonUtil.firstToUpperCase(d);
                                            }
                                            isFirst = false;
                                        }
                                    }
                                    String[] lis = fileText.split("\n");
                                    fileText = "";
                                    for (int ss = 0; ss < lis.length; ss++) {
                                        lis[ss] = CommonUtil.replaceWord(lis[ss], id, "getBinding()\\." + id);
                                        String node = "parent\\.";
                                        lis[ss] = CommonUtil.replaceWord(lis[ss], node, node + "getBinding()\\.");
                                        if (lis[ss].length() > 0) {
                                            fileText += lis[ss] + "\n";
                                        }
                                    }
                                }
                            }
                        }
                        FileUtils.writeStringToFile(file, fileText);
                        writeModel(file, pkg, activity, basePath);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
    }




    /**
     * 每个activity写入对应的model
     * @param file
     * @param basePath
     */
    private static void writeModel(File file,String pkg,String activity,String basePath){
        String path = file.getPath().substring(0,file.getPath().indexOf("."));
        path+="ViewModel";
        path+=file.getPath().substring(file.getPath().indexOf("."));
        File modelPath = new File(path);
        if(!modelPath.exists()){
            Map<String,Object> data = new HashMap<>();
            data.put("package",pkg);
            data.put("activity",activity);
            String tempPath = basePath+"template/";
            String xxxaction = TemplateUtil.create(tempPath,"viewmodel.vm",data);
            try {
                JsonXmlUtils.stringToFile(xxxaction, modelPath);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    public static void getFiles(String path, ArrayList<File> list,String...fitter) throws Exception {
        //目标集合fileList
        File file = new File(path);
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File fileIndex : files) {
                //如果这个文件是目录，则进行递归搜索
                if (fileIndex.isDirectory()) {
                    getFiles(fileIndex.getPath(),list,fitter);
                } else {
                    //如果文件是普通文件，则将文件句柄放入集合中
                    String filename = fileIndex.getName();
                    if(!filename.endsWith("java")){
                        continue;
                    }
                    filename =filename.substring(0,filename.indexOf("."));
                    boolean has = false;
                    for(String f:fitter){
                        if(filename.endsWith(f)){
                            has = true;
                            break;
                        }
                    }
                    if(has){
                        list.add(fileIndex);
                    }
                }
            }
        }
    }
}
